<template>
    <div class="magazine" :style="`background-color:${resDetail.backgroundColor}`">

      <!-- diy render cpt -->
      <!-- <diy-cpt ref="diy-top" :stylex="true"></diy-cpt> -->

      <div v-show="isReady">

        <!-- title -->
        <section class="sec-title" v-if="resDetail.is_show_magazine_message == 1">
          <h2>{{resDetail.jsapi_title}}</h2>
          <div class="time-author">
            <span class="magazineTime">{{resDetail.info.create_time}}</span>
            <span class="magazineAuthor">{{resDetail.shop_title}}</span>
          </div>
        </section>

        <!-- des -->
        <section :class="['sec-des', 'members_con', { 'noMargin': resDetail.hasMargin != 1 }]">
          <!-- diy -->
          <van-list v-model="diyList.loading"
                      :finished="diyList.finished"
                      :error.sync="diyList.error"
                      error-text="请求失败，点击重新加载"
                      finished-text=""
                      @load="onLoadDiy">
            <magazine-tpl :tplData="resDetail._diyHtml"></magazine-tpl>
          </van-list>
          <!-- <magazine-tpl :tplData="resDetail._diyHtml"></magazine-tpl> -->

          <!-- <div v-show="resDetail.topHtml" v-html="resDetail.topHtml" class="des-diy members_con noMargin">
          </div>
          <div v-show="resDetail.diyHtml" v-html="resDetail.diyHtml" class="des-diy members_con noMargin">
          </div>
          <div v-show="resDetail.bottomHtml" v-html="resDetail.bottomHtml" class="des-diy members_con noMargin">
          </div> -->
        </section>

        <!-- share -->
        <section v-if="resDetail.isShowShareCard==1">
          <img v-if="resDetail.fx_card_url" :src="resDetail.fx_card_url" style="width:100%;margin:0 auto;">
        </section>

        <!-- msgs -->
        <section class="sec-msgs" v-if="resDetail.is_allow_magazine_message==1">
          <div class="area">
            <span class="liner_detail"></span>
            <p>精选留言</p>
            <span class="liner_detail"></span>
          </div>

          <!-- lists -->
          <div class="msgs">
            <van-list
              v-model="msgs.loading"
              :finished="msgs.finished"
              finished-text=""
              :error.sync="msgs.error"
              error-text="请求失败，点击重新加载"
              @load="onMsgPageLoad"
            >
              <div class="msg" v-for="(item) in message_list" :key="item.message_id">
                <div class="msg-top">
                  <div>
                    <img :src="item.head_img">
                    <span>{{item.nick_name}}</span>
                  </div>
                  <span>{{item.create_time}}</span>
                </div>
                <div class="msg-middle">
                  {{item.content}}
                </div>
                <div class="msg-reply" v-if="item.reply">
                  <p><span>商家回复：&nbsp;</span>{{item.reply.reply_content}}</p>
                </div>
                <div class="msg-bottom">
                  <span @click="onMsgItemPraise(item)">
                    <span>{{item.praize_num}}</span>
                    <span :class="['zan',{'good-icon-praised':item.is_prise,'good-icon':!item.is_prise}]"></span>
                  </span>
                </div>
              </div>
            </van-list>
          </div>
          <div></div>
        </section>

        <!-- post msg -->
        <section class="sec-post-msg">
          <div class="part1">
            <div>
              <textarea name="content" placeholder="写几句准备发帖子啦...." v-model="postMsg.content"></textarea>
            </div>
            <div>
              <div class="button cancel" @click="onCancelMsgPopClick">取消</div>
              <div class="button post" @click="onPostMsg">发布</div>
            </div>
          </div>
        </section>


        <!-- bottom -->

        <section class="sec-bottom" v-if="resDetail.is_allow_magazine_message==1 || resDetail.is_praise_share==1">

          <button v-if="resDetail.is_allow_magazine_message==1" @click="onShowPostMsgClick"><img src="https://img.wifenxiao.com/h5-wfx/images/shop/magazine/icon-edit.png" />说点什么吧…</button>
          <div v-if="resDetail.is_wx == 1 && (resDetail.is_praise_share == 1 || resDetail.is_fx_share == 1)" class="share" >
            <p>
              <img src="https://img.wifenxiao.com/h5-wfx/images/shop/magazine/icon-view.png" />
              <span>{{Number(resDetail.info.pv)>999?'999+':resDetail.info.pv}}</span>
            </p>
            <p v-if="resDetail.is_praise_share==1" @click="onDetailPraise">
              <span :class="{'good-icon-praised':resDetail.praise==1,'good-icon':resDetail.praise==0}"></span>
              <span>{{praise_num}}</span>
            </p>
          </div>
        </section>

      </div>

      <!-- diy render cpt -->
      <!-- <diy-cpt ref="diy-bottom" :libMin="true" :layzr="true" :swipe="true" :main="true" :indexComm="true" :map="true"></diy-cpt> -->
      <!-- 授权弹出框 -->
      <small-login ref="smalllogin"></small-login>
    </div>
</template>

<script>
/**
 * @description 专题diy详情
 * @author gaogm
 */

import Vue from 'vue'
import magazineTpl from './magazineTpl/index'
import small from '@/smallapp/small'
import SmallLogin from '@/components/SmallLogin/smallLogin.vue'
import { openPage, mpShare} from '@/utils/utils'

// import { reqGetMagazine, reqPostMagazinePraise, reqPostMagazineReleaseMsg, reqPostMagazineMsgPraise } from '@/api/shop/index'
import { magazineDetailDiyHtml, magazineMessageList, reqPostMagazinePraise, reqPostMagazineReleaseMsg, reqPostMagazineMsgPraise } from '@/api/shop/index'

export default Vue.extend({
  components: {
    magazineTpl,
    SmallLogin
  },

  data() {
    return {
      magazineId: '',
      lastpid: '',
      resDetail: {
        info: '',
        _diyHtml: []
      },
      message_list: [],
      postMsg: {
        content: ''
      },
      diyList: {
        loading: false,
        finished: false,
        error: false,
        page: 2
      },
      msgs: {
        finished: false,
        loading: false,
        error: false,
        pageSize: 10,
        page: 2
      },
      isReady: false,
      praise_num: ''
    }
  },
  mounted() {
    // 小程序触底加载更多
    window.addEventListener('reachbottom', () => {
      this.onMsgPageLoad()
    })
      window.addEventListener('wxload', query => {
        // // console.log(query, '分享参数')
        this.magazineId = this.$route.query.id || query.id
        this.lastpid = this.$route.query.lastpid || query.lastpid
        this.init(true)
        small.HandleShareParams()
      })

      window.addEventListener('wxshow', () => {
        if (!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
      })
  },
  methods: {
    onDetailPraise() {
      if (this.resDetail.praise == 1) { return }
      reqPostMagazinePraise({
        'id': this.resDetail.info.magazine_id
      }).then(res => {
        if (res.status == 1) {
          this.resDetail.praise = 1
          this.praise_num = Number(this.praise_num) + 1
        }
      }).catch(_ => {})
    },
    onMsgItemPraise(item) {
      if (item.is_prise) { return }
      reqPostMagazineMsgPraise({
        'message_id': item.message_id
      }).then(res => {
        if (res.status == 1) {
          this.init()
        }
      }).catch(_ => {})
    },
    onPostMsg() {
      reqPostMagazineReleaseMsg({
        'magazine_id': this.resDetail.info.magazine_id,
        'content': this.postMsg.content
      }).then(res => {
        if (res.status == 1) {
          this.postMsg.content = ''
          this.$Error('发布成功')
          this.onCancelMsgPopClick()
          this.init()
        } else {
          this.$Error(res.msg)
        }
      }).catch(_ => {})
    },
    // 留言数据加载更多
    onMsgPageLoad() {
      magazineMessageList({
        'id': this.magazineId,
        'p': this.msgs.page
      }).then(res => {
        this.msgs.loading = false
        const data = res.data.message_list
        if (res.status == 1) {
          if (data && data.length) {
            this.message_list.push(...data)
            this.msgs.page++
          } else {
            this.msgs.finished = true
          }
        } else {
          this.msgs.error = true
        }
      }).catch(_ => {
        this.msgs.error = true
      })
    },
    // diy数据加载更多
    onLoadDiy() {
      magazineDetailDiyHtml({
        'lastpid': this.lastpid,
        'id': this.magazineId,
        'p': this.diyList.page
      }).then(res => {
        this.diyList.loading = false
        if (res.status == 1) {
          if (res.data._diyHtml && res.data._diyHtml.length) {
            this.resDetail._diyHtml.push(...res.data._diyHtml)
            this.diyList.page++
            this.ProcessingLoading()
          } else {
            this.diyList.finished = true
          }
        } else {
          this.diyList.error = true
        }
      }).catch(() => {
        this.diyList.error = true
      })
    },
    onShowPostMsgClick() {
      document.getElementsByClassName('sec-post-msg')[0].style.display = 'block'
    },
    onCancelMsgPopClick() {
      document.querySelector('.sec-post-msg').style.display = 'none'
    },
    init(isFirst = false) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 50000)

      if (!this.magazineId) { return }
      // diy数据
      magazineDetailDiyHtml({
        'lastpid': this.lastpid,
        'id': this.magazineId,
        'p': 1
      }).then(res => {
        this.isReady = true
        this.$loadingWrap.close()
        const data = res.data
        this.resDetail = data
        this.ProcessingLoading()
        this.praise_num = data.info ? data.info.praise_num : ''
        if (res.status == 1) {
          if (res.data && res.data.redirect_url) {
            openPage(res.data.redirect_url, 1)
          }
          const resData = res.data
            // TODO 小程序分享
            const pid = small.wxCache('global_login_info') ? small.wxCache('global_login_info').uid : '0'
            const option = {
              title: resData.jsapi_title,
              imgUrl: resData.jsapi_img,
              shareParam: res.data.jsapi_url ? res.data.jsapi_url.split('?')[1] : `id=${this.magazineId}&sid=${small.globalData.shopId}&pid=${pid}&lastpid=${pid}`
            }
            mpShare (true, true, '/goods/pages/magazine/index', option)
          // TODO 小程序设置标题
            wx.setNavigationBarTitle({
              title: this.resDetail.page_title
            })
          this.$nextTick(() => {
            // 对应 bottom 查看，点赞条件；不显示时其他内容居中
            const $bottomSec = document.querySelector('.sec-bottom')
            if (!(this.resDetail.is_wx == 1 && (this.resDetail.is_praise_share == 1 || this.resDetail.is_fx_share == 1))) {
              $bottomSec.style.justifyContent = 'center'
            }
            if ($bottomSec.childElementCount === 0) {
              $bottomSec.style.display = 'none'
            }
          })

          // this.$refs['diy-bottom'].startLoadJsMap()
        }
      }).catch(_ => {
        this.$loadingWrap.close()
      })

      // 留言数据
      magazineMessageList({
        'id': this.magazineId,
        'p': 1
      }).then(res => {
        this.msgs.loading = false
        const data = res.data.message_list
        if (res.status == 1) {
          if (data && data.length) {
            this.message_list = data
          } else {
            this.msgs.finished = true
          }
        } else {
          this.msgs.error = true
        }
      }).catch(() => {
        this.$loadingWrap.close()
      })
    },
    ProcessingLoading() {
      let videoSort = 0;
      let tplData = this.resDetail._diyHtml
      // console.log('ProcessingLoading....._diyHtml', tplData)
      for (let i = 0; i < tplData.length; i++) {
        if (tplData[i].type == 14) {
          if (typeof isPlayArr === "undefined") {
            var isPlayArr = [];
          }
          isPlayArr[videoSort] = false;
          tplData[i].content.videoSort = videoSort;
          videoSort++;
          tplData[i].content.isPlayArr = isPlayArr;
          // console.log('ProcessingLoading.....tplData', tplData[i])
        }
      }
      this.resDetail._diyHtml = tplData
    },
  }
})
</script>

<style lang="scss">
@import 'src/styles/variables.scss';
@import "src/styles/mixin";

.magazine {
  .good-icon-praised {
    background: url() top left no-repeat;
  }
  .good-icon {
    background: url() top left no-repeat;
  }

  .sec-title {
    background: #fff;
    padding: 30px 20px 40px;
    border-radius: 0px 0px 20px 20px;
    margin-bottom:20px;
    h2 {
      font-size: 28px;
      line-height: 1.4;
      font-weight: bold;
    }
    .time-author{
      margin-top: 14px;
      font-size: 24px;
      .magazineTime{
        color: #999;
      }
      .magazineAuthor{
        margin-left: 20px;
        color: #687A92;
      }
    }
  }
  .members_con{
    margin:0 20px;
    &.noMargin{
      margin:0;
    }
  }

  .sec-liked {
    background-color: white;
    font-size: 28px;
    color: #999;
    padding: 16px 20px;
    margin: 30px auto 0;
    line-height: 40px;
    & > div {
      display: inline-block;
      line-height: 40px;
    }
    div:last-child {
      margin-left: 30px;
      span:first-child {
        display: inline-block;
        vertical-align: top;
        width: 36px;
        height: 36px;
        background-size: 100%;
      }
    }
  }

  .sec-msgs {
    .area {
      display:flex;
      justify-content: center;
      align-items: center;
      font-size: 28px;
      padding: 30px 0;
      p {
        padding: 0 16px;
        color: #999;
        display: inline-block;
      }
      .liner_detail{
        height: 2px;
        width: 165px;
        background: #E6E6E6;
        position: relative;
        &::after{
          content: '';
          position: absolute;
          background:#E6E6E6 ;
          width: 8px;
          height: 8px;
          top: 0;
          transform: rotate(-45deg) translateY(-50%);
        }
        &:first-child{
          &::after{
            right: -3px;
          }
        }
        &:last-child{
          &::after{
            left: 3px;
          }
        }
      }
    }

    .msgs {
      padding: 0px 20px 90px;
      .msg {
        padding: 20px;
        margin-top: 20px;
        background-color: white;
        border-radius: 20px;
        &-top {
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          > div {
            img {
              border-radius: 50%;
              width: 66px;
              height: 66px;
            }
            span {
              margin-left: 15px;
              font-size: 24px;
              color: #333;
              font-weight: 500;
            }
          }
          > span {
            font-size: 24px;
            color: #999;
            font-weight: 500;
          }
        }
        &-middle {
          padding: 20px 0;
          font-size: 26px;
          color: #333;
          font-weight: 500;
          overflow: scroll;
        }
        &-reply {
          padding: 20px;
          background:rgba(247,247,247,1);
          border-radius: 10px;
          > span {
            color: #333;
            font-size: 26px;
            font-weight: 500;
          }
          > p {
            line-height: 1.5;
            font-size: 26px;
            color: #666;
            font-weight: 500;
            overflow: scroll;
          }
        }
        &-bottom {
          margin-top: 20px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: flex-end;
          font-size: 26px;
          color: #333;
          font-weight: bold;
          > span {
            span:first-child {
              padding-right: 16px;
            }
            span:last-child {
              vertical-align: bottom;
              display: inline-block;
              background-size: 100%;
              width: 36px;
              height: 36px;
            }
          }
        }
      }
    }
  }

  .sec-post-msg {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #f7f7f7;
    z-index: 2000;
    overflow: hidden;

    .part1 {
      min-height: 100px;
      margin: 25px;
      div:first-child {
        textarea {
          display: block;
          width: 100%;
          min-height: 580px;
          line-height: 40px;
          font-size: 26px;
          padding: 25px;
          resize:none;
          border-radius: 20px;
          background:#fff;
        }
      }
      div:nth-child(2) {
        display:flex;
        justify-content: space-between;
        padding: 25px 0;
        .button {
          display:inline-block;
          width: 340px;
          padding: 28px 0;
          border: 2px solid #F21228;
          border-radius: 10px;
          font-size: 26px;
        }
        .cancel {
          color: #F21228;
          background-color: white;
          text-align:center;
        }
        .post {
          margin-left: 20px;
          background: #F21228;
          color: white;
          text-align:center;
        }
      }
    }

  }

  .sec-bottom {
    position: fixed;
    width: 100%;
    max-width: 750px;
    height: 100px;
    bottom: 0;
    z-index: 11;
    border-top: 2px solid #f3f3f3;
    background: #fff;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    & > button {
      width: 60%;
      color: #999;
      font-size: 28px;
      background: #F7F7F7;
      border-radius: 34px;
      border: none;
      text-align: left;
      padding: 20px 0 20px 30px;
      img {
        width: 26px;
        height: 26px;
        margin-right: 18px;
      }
    }
    & > .share {
      width: 40%;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-around;
      p {
        font-size: 26px;
        color: #333;
        font-weight: bold;
      }
      p:first-of-type {
        img {
          width: 32px;
          height: 22px;
          margin-right: 10px;
          vertical-align: middle;
        }
      }
      p:last-of-type {
        span:first-child {
          display: inline-block;
          width: 36px;
          height: 36px;
          background-size: 100%;
          margin-right: 14px;
          vertical-align: bottom;
        }
      }
    }
  }
}
</style>